import React, { useState } from 'react';
import { Clock, Search, Filter, Eye, Download, Calendar, User, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';

const WorkflowHistory = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterWorkflow, setFilterWorkflow] = useState('all');
  const [dateRange, setDateRange] = useState('7days');
  const [selectedRecord, setSelectedRecord] = useState(null);

  // 模拟历史记录数据
  const historyRecords = [
    {
      id: 'WF-2024-001',
      workflowName: '用户注册审批流程',
      workflowId: 1,
      status: 'completed',
      startTime: '2024-01-20 14:30:25',
      endTime: '2024-01-20 14:35:12',
      duration: '4分47秒',
      initiator: '张三',
      triggerType: '手动触发',
      executionLog: '流程正常执行完成，用户审批通过',
      errorMessage: null,
      outputData: { userId: '12345', status: 'approved', approver: '管理员' }
    },
    {
      id: 'WF-2024-002',
      workflowName: '文件上传处理流程',
      workflowId: 2,
      status: 'completed',
      startTime: '2024-01-20 13:45:10',
      endTime: '2024-01-20 13:47:32',
      duration: '2分22秒',
      initiator: '李四',
      triggerType: '事件触发',
      executionLog: '文件处理完成，已生成缩略图',
      errorMessage: null,
      outputData: { fileId: 'file_789', size: '2.5MB', thumbnail: 'generated' }
    },
    {
      id: 'WF-2024-003',
      workflowName: '异常处理流程',
      workflowId: 5,
      status: 'failed',
      startTime: '2024-01-20 13:15:30',
      endTime: '2024-01-20 13:18:45',
      duration: '3分15秒',
      initiator: '系统',
      triggerType: '自动触发',
      executionLog: '异常分析节点执行失败',
      errorMessage: '连接数据库超时，无法获取异常详情',
      outputData: null
    },
    {
      id: 'WF-2024-004',
      workflowName: '数据备份流程',
      workflowId: 4,
      status: 'completed',
      startTime: '2024-01-20 02:00:00',
      endTime: '2024-01-20 02:45:30',
      duration: '45分30秒',
      initiator: '定时任务',
      triggerType: '定时触发',
      executionLog: '数据备份完成，备份文件已上传到云存储',
      errorMessage: null,
      outputData: { backupSize: '1.2GB', location: 'cloud-storage', checksum: 'abc123' }
    },
    {
      id: 'WF-2024-005',
      workflowName: '用户注册审批流程',
      workflowId: 1,
      status: 'cancelled',
      startTime: '2024-01-19 16:20:15',
      endTime: '2024-01-19 16:22:05',
      duration: '1分50秒',
      initiator: '王五',
      triggerType: '手动触发',
      executionLog: '用户主动取消申请',
      errorMessage: null,
      outputData: { userId: '12346', status: 'cancelled', reason: 'user_cancelled' }
    },
    {
      id: 'WF-2024-006',
      workflowName: '文件上传处理流程',
      workflowId: 2,
      status: 'failed',
      startTime: '2024-01-19 15:30:20',
      endTime: '2024-01-19 15:31:45',
      duration: '1分25秒',
      initiator: '赵六',
      triggerType: '事件触发',
      executionLog: '病毒扫描检测到恶意文件',
      errorMessage: '文件包含病毒，已自动删除',
      outputData: { fileId: 'file_456', status: 'deleted', reason: 'virus_detected' }
    },
    {
      id: 'WF-2024-007',
      workflowName: '数据备份流程',
      workflowId: 4,
      status: 'completed',
      startTime: '2024-01-19 02:00:00',
      endTime: '2024-01-19 02:42:15',
      duration: '42分15秒',
      initiator: '定时任务',
      triggerType: '定时触发',
      executionLog: '数据备份完成',
      errorMessage: null,
      outputData: { backupSize: '1.1GB', location: 'cloud-storage', checksum: 'def456' }
    }
  ];

  // 工作流列表
  const workflows = [
    { id: 1, name: '用户注册审批流程' },
    { id: 2, name: '文件上传处理流程' },
    { id: 4, name: '数据备份流程' },
    { id: 5, name: '异常处理流程' }
  ];

  // 过滤历史记录
  const filteredRecords = historyRecords.filter(record => {
    const matchesSearch = record.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         record.workflowName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         record.initiator.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || record.status === filterStatus;
    const matchesWorkflow = filterWorkflow === 'all' || record.workflowId.toString() === filterWorkflow;
    
    // 日期过滤
    const recordDate = new Date(record.startTime);
    const now = new Date();
    let matchesDate = true;
    
    switch (dateRange) {
      case '1day':
        matchesDate = (now - recordDate) <= 24 * 60 * 60 * 1000;
        break;
      case '7days':
        matchesDate = (now - recordDate) <= 7 * 24 * 60 * 60 * 1000;
        break;
      case '30days':
        matchesDate = (now - recordDate) <= 30 * 24 * 60 * 60 * 1000;
        break;
      default:
        matchesDate = true;
    }
    
    return matchesSearch && matchesStatus && matchesWorkflow && matchesDate;
  });

  const getStatusBadge = (status) => {
    const statusConfig = {
      completed: { color: 'bg-green-100 text-green-800', text: '成功' },
      failed: { color: 'bg-red-100 text-red-800', text: '失败' },
      cancelled: { color: 'bg-gray-100 text-gray-800', text: '取消' },
      timeout: { color: 'bg-yellow-100 text-yellow-800', text: '超时' }
    };
    
    const config = statusConfig[status] || statusConfig.completed;
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'failed':
        return <XCircle className="w-5 h-5 text-red-600" />;
      case 'cancelled':
        return <AlertTriangle className="w-5 h-5 text-gray-600" />;
      default:
        return <Clock className="w-5 h-5 text-gray-600" />;
    }
  };

  const getTriggerTypeBadge = (type) => {
    const typeConfig = {
      '手动触发': { color: 'bg-blue-100 text-blue-800' },
      '事件触发': { color: 'bg-purple-100 text-purple-800' },
      '定时触发': { color: 'bg-orange-100 text-orange-800' },
      '自动触发': { color: 'bg-cyan-100 text-cyan-800' }
    };
    
    const config = typeConfig[type] || typeConfig['手动触发'];
    return (
      <Badge variant="secondary" className={`${config.color} hover:${config.color}`}>
        {type}
      </Badge>
    );
  };

  const completedCount = historyRecords.filter(r => r.status === 'completed').length;
  const failedCount = historyRecords.filter(r => r.status === 'failed').length;
  const cancelledCount = historyRecords.filter(r => r.status === 'cancelled').length;
  const avgDuration = '15分32秒'; // 模拟平均执行时间

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <Clock className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    执行历史
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    查看工作流执行历史记录
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：搜索和筛选 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索执行记录..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={dateRange} onValueChange={setDateRange}>
                <SelectTrigger className="w-32">
                  <Calendar className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1day">今天</SelectItem>
                  <SelectItem value="7days">7天内</SelectItem>
                  <SelectItem value="30days">30天内</SelectItem>
                  <SelectItem value="all">全部</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterWorkflow} onValueChange={setFilterWorkflow}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择工作流" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部工作流</SelectItem>
                  {workflows.map(workflow => (
                    <SelectItem key={workflow.id} value={workflow.id.toString()}>
                      {workflow.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="completed">成功</SelectItem>
                  <SelectItem value="failed">失败</SelectItem>
                  <SelectItem value="cancelled">取消</SelectItem>
                </SelectContent>
              </Select>

              <Button variant="outline">
                <Download className="w-4 h-4 mr-2" />
                导出
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总执行次数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{historyRecords.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Clock className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">成功执行</p>
                  <p className="text-2xl font-bold text-green-600">{completedCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">执行失败</p>
                  <p className="text-2xl font-bold text-red-600">{failedCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <XCircle className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">平均时长</p>
                  <p className="text-2xl font-bold text-purple-600">{avgDuration}</p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Clock className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 历史记录列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>执行信息</TableHead>
                  <TableHead>工作流</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>触发方式</TableHead>
                  <TableHead>发起人</TableHead>
                  <TableHead>开始时间</TableHead>
                  <TableHead>执行时长</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredRecords.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell>
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(record.status)}
                        <div>
                          <p className="font-medium text-material-grey-900">{record.id}</p>
                          <p className="text-sm text-material-grey-500">
                            {record.endTime ? `结束于 ${record.endTime}` : '执行中'}
                          </p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{record.workflowName}</span>
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(record.status)}
                    </TableCell>
                    <TableCell>
                      {getTriggerTypeBadge(record.triggerType)}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <User className="w-4 h-4 text-material-grey-500" />
                        <span className="text-sm text-material-grey-700">{record.initiator}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-600">{record.startTime}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-600">{record.duration}</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => setSelectedRecord(record)}
                          >
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-2xl">
                          <DialogHeader>
                            <DialogTitle>执行详情 - {selectedRecord?.id}</DialogTitle>
                          </DialogHeader>
                          {selectedRecord && (
                            <div className="space-y-6">
                              {/* 基本信息 */}
                              <div className="grid grid-cols-2 gap-4">
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">工作流名称</label>
                                  <p className="text-material-grey-900">{selectedRecord.workflowName}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">执行状态</label>
                                  <div className="mt-1">{getStatusBadge(selectedRecord.status)}</div>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">触发方式</label>
                                  <div className="mt-1">{getTriggerTypeBadge(selectedRecord.triggerType)}</div>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">发起人</label>
                                  <p className="text-material-grey-900">{selectedRecord.initiator}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">开始时间</label>
                                  <p className="text-material-grey-900">{selectedRecord.startTime}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">执行时长</label>
                                  <p className="text-material-grey-900">{selectedRecord.duration}</p>
                                </div>
                              </div>

                              {/* 执行日志 */}
                              <div>
                                <label className="text-sm font-medium text-material-grey-600">执行日志</label>
                                <div className="mt-2 p-3 bg-material-grey-50 rounded-lg">
                                  <p className="text-sm text-material-grey-800">{selectedRecord.executionLog}</p>
                                </div>
                              </div>

                              {/* 错误信息 */}
                              {selectedRecord.errorMessage && (
                                <div>
                                  <label className="text-sm font-medium text-red-600">错误信息</label>
                                  <div className="mt-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                                    <p className="text-sm text-red-800">{selectedRecord.errorMessage}</p>
                                  </div>
                                </div>
                              )}

                              {/* 输出数据 */}
                              {selectedRecord.outputData && (
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">输出数据</label>
                                  <div className="mt-2 p-3 bg-material-grey-50 rounded-lg">
                                    <pre className="text-sm text-material-grey-800 whitespace-pre-wrap">
                                      {JSON.stringify(selectedRecord.outputData, null, 2)}
                                    </pre>
                                  </div>
                                </div>
                              )}
                            </div>
                          )}
                        </DialogContent>
                      </Dialog>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredRecords.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <Clock className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的记录' : '暂无执行历史'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '当有工作流执行时，历史记录将显示在这里'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default WorkflowHistory;
